package net.xiaochengxu.dining.utils;

import java.io.UnsupportedEncodingException;
import java.util.*;

public class PropertyUtil {

	private static Map instance = Collections.synchronizedMap(new HashMap());
	protected String sourceUrl;
	protected ResourceBundle resourceBundle;
	private static Map convert = Collections.synchronizedMap(new HashMap());

	protected PropertyUtil(String sourceUrl) {
		this.sourceUrl = sourceUrl;
		load();
	}

	public static PropertyUtil getInstance(String sourceUrl) {
		PropertyUtil manager;
		manager = (PropertyUtil) instance.get(sourceUrl);
		if (manager == null) {
			manager = new PropertyUtil(sourceUrl);
			instance.put(sourceUrl, manager);
		}
		return manager;
	}

	private synchronized void load() {
		try {
			resourceBundle = ResourceBundle.getBundle(sourceUrl);
		} catch (Exception e) {
			e.printStackTrace();
			throw new RuntimeException((new StringBuilder()).append("sourceUrl = ").append(sourceUrl)
					.append("file load error!").toString(), e);
		}
	}

	public String getProperty(String key) {
		try {
			return new String(resourceBundle.getString(key).getBytes("iso-8859-1"), "utf-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
			return resourceBundle.getString(key);
		}

	}

	public Map readyConvert() {
		String key;
		String value;
		for (Enumeration enu = resourceBundle.getKeys(); enu.hasMoreElements(); convert.put(value, key)) {
			key = (String) enu.nextElement();
			value = resourceBundle.getString(key);
		}

		return convert;
	}

	public Map readyConvert(ResourceBundle resourcebundle) {
		String key;
		String value;
		for (Enumeration enu = resourcebundle.getKeys(); enu.hasMoreElements(); convert.put(value, key)) {
			key = (String) enu.nextElement();
			value = resourcebundle.getString(key);
		}

		return convert;
	}

	public static void main(String[] args) {
		PropertyUtil propertyUtil = PropertyUtil.getInstance("project");
		System.out.println(propertyUtil.getProperty("contextPath"));
	}
}
